/*
 * Copyright 2018 Google LLC.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.google.cloud.tools.jib.plugins.common;

import com.google.cloud.tools.jib.event.events.TimerEvent;
import com.google.cloud.tools.jib.event.events.TimerEvent.State;
import java.util.function.Consumer;

/** Handles {@link TimerEvent}s by producing log messages. */
public class TimerEventHandler implements Consumer<TimerEvent> {

  /**
   * Gets a {@link StringBuilder} prepended with tabulation based on the number of parents {@code
   * timer} has.
   *
   * @param timer the {@link TimerEvent.Timer} to base the tabulation on
   * @return a new {@link StringBuilder}
   */
  private static StringBuilder getTabs(TimerEvent.Timer timer) {
    StringBuilder tabs = new StringBuilder();
    while (timer.getParent().isPresent()) {
      tabs.append("\t");
      timer = timer.getParent().get();
    }
    return tabs;
  }

  /**
   * Builds the log message for a {@link TimerEvent}, based on its state and duration.
   *
   * @param timerEvent the {@link TimerEvent}
   * @return the built log message
   */
  private static String buildLogMessage(TimerEvent timerEvent) {
    StringBuilder logMessageBuilder = getTabs(timerEvent.getTimer());

    if (timerEvent.getState() == State.START) {
      return logMessageBuilder.append("TIMING\t").append(timerEvent.getDescription()).toString();

    } else {
      return logMessageBuilder
          .append("TIMED\t")
          .append(timerEvent.getDescription())
          .append(" : ")
          .append(timerEvent.getDuration().toNanos() / 1000 / 1000.0)
          .append(" ms")
          .toString();
    }
  }

  private final Consumer<String> logMessageConsumer;

  /**
   * Creates a new {@link TimerEventHandler} with a consumer for log messages generated by handling
   * {@link TimerEvent}s.
   *
   * @param logMessageConsumer the log message consumer
   */
  public TimerEventHandler(Consumer<String> logMessageConsumer) {
    this.logMessageConsumer = logMessageConsumer;
  }

  @Override
  public void accept(TimerEvent timerEvent) {
    logMessageConsumer.accept(buildLogMessage(timerEvent));
  }
}
